from flask import request, json
from flask_cors import CORS
import requests
from model import *
# from mq import mq_connect
import redis

app = create_app()
app.app_context().push()
db.create_all()
# channel = mq_connect()
redis_conn = redis.Redis(host= 'redis', port = 6379, decode_responses=True)
CORS(app)

@app.route('/result', methods=["POST", "GET"])
def order():
    if(request.method == "POST"):
        data = request.get_json()
        print(data)
        print(redis_conn.hgetall('orderinfo'))
        data = json.loads(data)
        uid = data["uid"]
        orders = redis_conn.hget('orderinfo', uid)
        orders = orders.split(" ")
        if(orders):
            print("redis")
            orderdetail = {}
            for order in orders:
                print(order)
                detail = redis_conn.hgetall(order)                
                orderdetail[order] = detail
                # 检查detail是否存在
            
        else:
            print("no-redis")
            orderss = Orderinfo.query.filter_by(userinfo_id=uid).all()
            if(orderss is None):
                return {
                    "status": 0,
                    "message": "None"}
            print("orders")
            orderdetail = {}
            for orderid in orderss:
                ordername = "order" + str(orderid.order_id)
                detail = redis_conn.hgetall(ordername)
                if(detail):
                    orderdetail[ordername] = detail
                else:
                    order = Order.query.get(orderid.order_id)
                    detail = {}
                    detail["uid"] = order.userinfo_id
                    userinfo = Userinfo.query.get(int(uid))
                    detail["name"] = userinfo.name
                    detail["studentID"] = userinfo.studentid
                    unit = Unit.query.get(order.unit_id)
                    dorm = Dorm.query.get(unit.dorm_id)
                    detail["dorm"] = dorm.dormid
                    detail["unit"] = unit.unitid
                    detail["num"] = order.num
                    detail["message"] = order.message
                    detail["status"] = int(order.status)
                    detail["time"] = str(order.time)
                    if(order.status):
                        info = Information.query.filter_by(userinfo_id=uid).first()
                        room = Room.query.get(info.room_id)
                        detail["room"] = room.roomid
                    ordername = "order" + str(orderid.order_id)
                    redis_conn.hmset(ordername, detail)
                    orderdetail[ordername] = detail
                orders = redis_conn.hget("orderinfo", uid)
                if(orders):
                    orders = orders + " " + ordername
                else:
                    orders = ordername
                redis_conn.hset("orderinfo", uid, orders)
        return orderdetail
    

if __name__ == "__main__":
    app.run(host = '0.0.0.0')